#include<iostream>
#include<pthread.h>
#include<unistd.h>
using namespace std;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ticket = 1000;

void* threadRountine(void* args)
{
    string name = static_cast<const char*>(args);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            cout << name << ", get a ticket:" << ticket-- << endl;
            usleep(1000);
        }
        else
        {
            cout << "没票了," << name << endl;
            pthread_cond_wait(&cond, &mutex);
        }
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
   pthread_t t1, t2, t3;
   pthread_create(&t1, nullptr, threadRountine,(void*)"thread-1");
   pthread_create(&t2, nullptr, threadRountine,(void*)"thread-2");
   pthread_create(&t3, nullptr, threadRountine,(void*)"thread-3");
   
   sleep(5);
   while(true)
   {
     /* pthread_cond_signal(&cond); */
     /*   pthread_cond_broadcast(&cond); */
         sleep(6);
         pthread_mutex_lock(&mutex);
         ticket += 100;
         pthread_mutex_unlock(&mutex);
         pthread_cond_signal(&cond);
   }

   pthread_join(t1, nullptr);
   pthread_join(t2, nullptr);
   pthread_join(t3, nullptr);
   return 0;
}